﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Collections;

namespace Spencen.Mobile.UI.Templating
{
    public class ObservableList : System.Collections.CollectionBase
    {
        public event ListChangedEventHandler ItemsChanged;

        public ObservableList()
        {
        }

        public ObservableList( IEnumerable enumerable ): this()
        {
            foreach ( var item in enumerable )
                Add( item );
        }

        public object this[ int index ]
        {
            get { return List[ index ]; }
            set { List[ index ] = value; }
        }    

        public void Add( object newItem )
        {
            List.Add( newItem );
        }

        protected override void OnInsertComplete( int index, object value )
        {
            base.OnInsertComplete( index, value );
            OnItemsChanged( new ListChangedEventArgs( ListChangedType.ItemAdded, index ) );
        }

        protected override void OnRemoveComplete( int index, object value )
        {
            base.OnRemoveComplete( index, value );
            OnItemsChanged( new ListChangedEventArgs( ListChangedType.ItemDeleted, index ) );
        }

        protected override void OnClearComplete()
        {
            base.OnClearComplete();
            OnItemsChanged( new ListChangedEventArgs( ListChangedType.Reset, 0 ) );
        }

        protected virtual void OnItemsChanged( ListChangedEventArgs e )
        {
            var handler = ItemsChanged;
            if ( handler != null )
                handler( this, e );
        }
    }
}
